package com.guangbao.handler;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.auth0.jwt.JWT;
import com.google.gson.Gson;
import com.guanbao.entity.ResponseMessage;
import com.guanbao.entity.User;
import com.guangbao.service.UserService;
import com.guangbao.service.impl.UserServiceImpl;
import com.guangbao.utils.TokenUtil;

public class LoginHandler extends HttpServlet {

	private static final long serialVersionUID = 6259476652569998211L;
	private UserService userService  = new UserServiceImpl();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/json;charset=utf-8");

		PrintWriter out = resp.getWriter();
		
		Gson gson = new Gson();
		
		ResponseMessage resM = new ResponseMessage();
		
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		
		if(username == null || username.trim().isEmpty()) {
			resM.setStatus(ResponseMessage.getStatusError());
			resM.setMsg("用户名不能为空");
			out.write(gson.toJson(resM));
			out.flush();
			out.close();
			return;
		}
		
		if(password == null || password.trim().isEmpty()) {
			resM.setStatus(ResponseMessage.getStatusError());
			resM.setMsg("密码不能为空");
			out.write(gson.toJson(resM));
			out.flush();
			out.close();
			return;
		}
		
		User user = userService.getUserByUsername(username);
		if(user == null) {
			resM.setStatus(ResponseMessage.getStatusError());
			resM.setMsg("用户名不存在");
			out.write(gson.toJson(resM));
			out.flush();
			out.close();
			return;
		}
		
		if(!password.equals(user.getPassword())) {
			
			resM.setStatus(ResponseMessage.getStatusError());
			resM.setMsg("用户名或密码错误");
			out.write(gson.toJson(resM));
			out.flush();
			out.close();
			return;
		}
		
		
		String token = TokenUtil.createJWT(user);
		if(token == null) {
			resM.setStatus(ResponseMessage.getStatusError());
			resM.setMsg("系统错误，请联系管理员!");
			out.write(gson.toJson(resM));
			out.flush();
			out.close();
			return;
		}
		
		resM.setStatus(ResponseMessage.getStatusOk());
		resM.setMsg("登录成功");
		resM.setData(token);
		out.write(gson.toJson(resM));
		
		out.flush();
		out.close();
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}

}